package com.gmrz.uaf.protocol.v1.processor;

import com.gmrz.service.challengestore.ChallengeStoreException;
import com.gmrz.uaf.common.Constants;
import com.gmrz.uaf.db.DAOException;
import com.gmrz.uaf.db.UAFDAOFactory;
import com.gmrz.uaf.db.UAFDBConnectionMgr;
import com.gmrz.uaf.db.dao.AuthenticatorDAO;
import com.gmrz.uaf.protocol.v1.schema.Authenticator;
import com.gmrz.uaf.protocol.v1.schema.DeviceDetails;
import com.gmrz.util.db.DBUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by chentaikun on 16/12/19.
 */
public class UAFUpdateCertStatusProcessor extends UAFBaseProcessor {

    private static final Logger LOG = LogManager.getLogger(UAFUpdateCertStatusProcessor.class);

    /**
     *
     * @param appID
     * @param userName
     * @param keyID
     * @throws SQLException
     * @throws DAOException
     */
    public int updateCertStatus(String appID , String userName,String keyID) throws SQLException, DAOException, ChallengeStoreException {
        Connection conn = UAFDBConnectionMgr.getConnection(false);
        int n = 0;
        try {
            AuthenticatorDAO adao = UAFDAOFactory.createAuthenticatorDAO(conn);
            Authenticator authenticator = adao.findAuthenticator(appID,  userName,  keyID);
            if(null != authenticator){
                if(authenticator.getCertificateExtendBean().getCertStatus() > Constants.CERT_STATUS_1){
                    n = 1;
                }else {
                    n = adao.updateCertStatus(authenticator.getID(), Constants.CERT_STATUS_1, Constants.CERT_STATUS_2);
                }

                String value = this.getServerConfig().getUasConfig(Constants.UAF_NOT_ACTIVITY_AUTHENTICATOR);
                if(com.gmrz.util.Strings.isNotBlank(value)) {
                    Integer v = Integer.parseInt(value);
                    if (v > 0) {
                        adao.updateCertStatus(authenticator.getID(), Constants.CERT_STATUS_2, Constants.CERT_STATUS_3);
                    }
                }

            }
            conn.commit();
        }catch (DAOException e1){
            conn.rollback();
            LOG.error("getCertInfos error",e1);
        }finally {
            DBUtil.close(conn);
        }

        return n;
    }

    public int updateCertActivityStatus(String appID , String userName,String keyID) throws SQLException, DAOException {
        Connection conn = null;
        int n = 0;
        try {
            conn = UAFDBConnectionMgr.getConnection();
            AuthenticatorDAO adao = UAFDAOFactory.createAuthenticatorDAO(conn);
            Authenticator authenticator = adao.findAuthenticator(appID,  userName,  keyID);
            n = adao.updateCertStatus(authenticator.getID(), Constants.CERT_STATUS_1, Constants.CERT_STATUS_3);

        }catch (DAOException e1){
            LOG.error("updateCertActivityStatus error",e1);
        }finally {
            DBUtil.close(conn);
        }

        return n;
    }

    public int activateCert(String appID, String hashedUserName, String authType, String transType, String activateType, String activateAppID, DeviceDetails devices) throws SQLException, DAOException {


        Connection conn = null;
        int n = 0;
        try {
            conn = UAFDBConnectionMgr.getConnection();
            AuthenticatorDAO adao = UAFDAOFactory.createAuthenticatorDAO(conn);

            Set<Authenticator> authenticators = adao.findUserNoDeviceDer( hashedUserName,  appID,  authType,  transType,  Constants.AuthenticatorStatus.ACTIVE.getStatus());
            if(null != authenticators){
                for(Authenticator a : authenticators){
                    if(a.getCertificateExtendBean().getCertStatus() == Constants.CERT_STATUS_3){
                        adao.updateCertStatus(a.getID(),Constants.CERT_STATUS_3,Constants.CERT_STATUS_2);
                    }
                }
            }

            Set<Authenticator> authenticatorSet = adao.findUserOnDevice(hashedUserName,appID, devices.getDeviceID(), authType, transType, Constants.AuthenticatorStatus.ACTIVE.getStatus());
            if(null != authenticatorSet && !authenticatorSet.isEmpty()){
                Iterator<Authenticator> it = authenticatorSet.iterator();
                while (it.hasNext()){
                    Authenticator authenticator = it.next();
                    int num = adao.updateCertStatus(authenticator.getID(), Constants.CERT_STATUS_2, Constants.CERT_STATUS_3);
                    if (num > 0) {
                        adao.updateCertExtend(activateAppID, authenticator.getID(), activateType);
                        n++;
                    }
                }
            }
        }catch (DAOException e1){
            LOG.error("activateCert error",e1);
            throw e1;
        }finally {
            DBUtil.close(conn);
        }

        return n;


    }
}
